/*
 * Copyright 2025 The JA-SIG Collaborative. All rights reserved.
 * distributed with this file and available online at
 */
package com.lap.auth.application.job;

import com.lap.auth.application.job.assembler.JobAssembler;
import com.lap.auth.application.job.command.CreateJobCmd;
import com.lap.auth.application.job.command.UpdateJobCmd;
import com.lap.auth.application.job.dto.JobDto;
import com.lap.auth.application.job.dto.QueryJobPageQuery;
import com.lap.auth.application.job.repository.JobQueryRepository;
import com.lap.auth.domain.job.Job;
import com.lap.auth.domain.job.repository.JobRepository;
import com.lap.auth.domain.job.service.JobValidator;
import com.lap.auth.shared.ports.SeqService;
import com.lap.framework.common.dto.page.PageResponse;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * 岗位应用服务层
 *
 * <ol>
 *   <li>不做业务规则，只做技术规则（加密/解密是技术实现，业务不关注）
 *   <li>取数，赋值，对象转换在这层执行
 *   <li>命名有规范，动词+领域名字
 *   <li>如查询比较多，建议分开领域QueryAppService,如:分页查询，分页查询返回关联字段
 * </ol>
 */
@RequiredArgsConstructor
@Service
public class JobAppService {

  private final JobAssembler jobAssembler;
  private final JobValidator jobValidator;
  private final SeqService seqService;
  private final JobRepository repository;
  private final JobQueryRepository queryRepository;

  public PageResponse<JobDto> queryJobsByPage(QueryJobPageQuery query) {
    return queryRepository.findByConditionPaged(query);
  }

  public Integer createJob(CreateJobCmd cmd) {
    String code = StringUtils.defaultIfBlank(cmd.getCode(), seqService.getSeq("DEPT", false));
    Job job = jobAssembler.toDomain(code, cmd);
    return repository.save(job);
  }

  public Integer updateJob(Integer id, UpdateJobCmd cmd) {
    Job snapshot = jobValidator.assertJobExists(id);
    Job job = jobAssembler.toDomain(id, snapshot.getCode(), cmd);
    return repository.save(job);
  }

  public Integer deleteJob(Integer id) {
    jobValidator.assertJobExists(id);
    return repository.deleteById(id);
  }
}
